package org.restoran.controller.filter;

import org.restoran.model.User;
import org.restoran.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 26.11.13
 * Time: 20:33
 * To change this template use File | Settings | File Templates.
 */

public class SeccuretyFilter implements Filter {

    @Autowired
    UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        if(((HttpServletRequest) req).getRequestURI().equals("/login")){
            chain.doFilter(req, res);
        } else {
            HttpServletRequest request = (HttpServletRequest) req;
            String key = request.getHeader("Accept-Content-Key");
            if(ifKeyExist(key)){
                chain.doFilter(req, res);
            } else {
                return;
            }
        }
    }

    @Override
    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean ifKeyExist(String key){
        Iterable<User> users = userService.findAll();
        for(User user:users){
            if(user.getKey().equals(key)){
                return true;
            }
        }
        return false;
    }
}
